package com.heima.gateway.auth;

import com.heima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * app过滤器
 */
@Component
public class AuthFitler implements GlobalFilter, Ordered {
    /**
     * 过滤器逻辑
     * 前后端约定：将JWT令牌设置的设置到请求头：token中   企业中约定俗成的：Authorization
     * 得到客户端提交令牌，解析令牌，获取载荷中用户信息，将用户ID设置到请求头，将请求路由到目标微服务
     *
     * @param exchange 封装请求响应对象
     * @param chain    过滤器链对象
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取请求，响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        try {
            //2. 判断请求路径 是否包含登陆
            String path = request.getURI().getPath();
            if (path.contains("/login")){
                //当前是登录请求 放行
                return chain.filter(exchange);
            }
            //3.从请求对象中获取请求头 判断是否为空
            String token = request.getHeaders().getFirst("token");
            if (StringUtils.isBlank(token)){
                //请求未提交 设置响应状态码404
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //4. 解析令牌 获取用户信息
            //4.1 如果校验JWT成功，在有效期内，得到用户载荷信息
            Claims claims = AppJwtUtil.getClaimsBody(token);

            //4.2 从用户载荷获取数据
            Object userId = claims.get("userId");
            Object userName = claims.get("userName");

            if (Integer.parseInt(userId.toString()) != 0){
                //表明用户是 手机号密码登录
                //4.3 将用户信息路由到其它微服务
                request.mutate().header("userId",userId.toString());
                request.mutate().header("userName",userName.toString());
            }
            Object equipmentId = claims.get("equipmentId");
            if (equipmentId!= null){
                //说明用户 选择不登陆先看看
                request.mutate().header("userId",userId.toString());
                request.mutate().header("equipmentId",equipmentId.toString());
            }

            return chain.filter(exchange);

        } catch (Exception e) {
            e.printStackTrace();
        }
        //其它情况 返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     * 过滤器执行顺序
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
